package com.meta.common.utils;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;

/**
 * 封住请求返回的参数
 *
 * @author Legend、
 */

public class Result {

    private String cookie;

    private int statusCode;

    private HashMap<String, Header> headerAll;

    private HttpEntity httpEntity;

    private String bodyCached;

    private Logger log = LoggerFactory.getLogger(Result.class);

    public String getCookie() {

        return cookie;
    }

    public void setCookie(String cookie) {

        this.cookie = cookie;
    }

    public int getStatusCode() {

        return statusCode;
    }

    public void setStatusCode(int statusCode) {

        this.statusCode = statusCode;
    }

    public HashMap<String, Header> getHeaders() {

        return headerAll;
    }

    public void setHeaders(Header[] headers) {

        headerAll = new HashMap<String, Header>();
        for (Header header : headers) {
            headerAll.put(header.getName(), header);
        }
    }

    public HttpEntity getHttpEntity() {

        return httpEntity;
    }

    public void setHttpEntity(HttpEntity httpEntity) {

        this.httpEntity = httpEntity;
    }

    /**
     * 注意：此方法只能调用一次，如果第二次调用，会直接取第一次生成的对象。
     *
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public String getBody() throws ParseException, IOException {

        if (bodyCached != null) {
            return bodyCached;
        }
        bodyCached = EntityUtils.toString(httpEntity, "UTF-8");
        if (log.isInfoEnabled()) {
            log.info(bodyCached);
        }
        return bodyCached;
    }

    /**
     * 注意：此方法只能调用一次，如果第二次调用，会直接取第一次生成的对象。
     *
     * @param encoding
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public String getBody(String encoding) throws ParseException, IOException {

        if (bodyCached != null) {
            return bodyCached;
        }
        bodyCached = EntityUtils.toString(httpEntity, encoding);
        if (log.isInfoEnabled()) {
            log.info(bodyCached);
        }
        return bodyCached;
    }

}
